import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/show_custom_bottom_sheet.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

typedef OnLongPressCallback = void Function(int position);

class GalleryPhotoViewWrapper extends StatefulWidget {
  GalleryPhotoViewWrapper({
    this.loadingBuilder,
    this.backgroundDecoration,
    this.minScale,
    this.maxScale,
    this.initialIndex,
    @required this.thumbGalleryItems,
    @required this.tagItems,
    this.originGalleryItems,
    this.scrollDirection = Axis.horizontal,
    this.onLongPressListener,
  }) : pageController = PageController(initialPage: initialIndex);

  final LoadingBuilder loadingBuilder;
  final Decoration backgroundDecoration;
  final dynamic minScale;
  final dynamic maxScale;
  final int initialIndex;
  final PageController pageController;
  final List<String> thumbGalleryItems;
  final List<String> originGalleryItems;
  final List<String> tagItems;
  final Axis scrollDirection;

  final OnLongPressCallback onLongPressListener;

  @override
  State<StatefulWidget> createState() {
    return _GalleryPhotoViewWrapperState();
  }
}

class _GalleryPhotoViewWrapperState extends State<GalleryPhotoViewWrapper> {
  int currentIndex;

  @override
  void initState() {
    currentIndex = widget.initialIndex;
    super.initState();
  }

  void onPageChanged(int index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: widget.backgroundDecoration,
        constraints: BoxConstraints.expand(
          height: MediaQuery.of(context).size.height,
        ),
        child: Stack(
          alignment: Alignment.bottomRight,
          children: <Widget>[
            GestureDetector(
              onLongPress: () {
                if(widget.onLongPressListener==null){
                  _editDyDialog();
                }else{
                  widget.onLongPressListener(currentIndex);
                }
              },
              child: PhotoViewGallery.builder(
                scrollPhysics: const BouncingScrollPhysics(),
                builder: _buildItem,
                itemCount: widget.thumbGalleryItems.length,
                loadingBuilder: widget.loadingBuilder,
                backgroundDecoration: widget.backgroundDecoration,
                pageController: widget.pageController,
                onPageChanged: onPageChanged,
                scrollDirection: widget.scrollDirection,
              ),
            ),
            Positioned(
              bottom: 20,
              right: 20,
              child: Container(
                child: Text(
                  "${currentIndex + 1}" +
                      "/" +
                      "${widget.thumbGalleryItems.length}",
                  style: const TextStyle(
                    color: Colors.white,
                    fontSize: 17.0,
                    decoration: null,
                  ),
                ),
              ),
            ),
            Positioned(
              top: 30,
              left: 0,
              child: IconButton(
                iconSize: 20,
                icon: Icon(
                  Icons.arrow_back,
                  color: Colors.white,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  PhotoViewGalleryPageOptions _buildItem(BuildContext context, int index) {
    String item = "";
    if (null == widget.originGalleryItems ||
        widget.originGalleryItems.length == 0) {
      item = widget.thumbGalleryItems[index];
    } else {
      item = widget.originGalleryItems[index];
    }
    var tag = item + widget.tagItems[index];
    return PhotoViewGalleryPageOptions(
      imageProvider: CachedNetworkImageProvider(item),
      initialScale: PhotoViewComputedScale.contained,
      minScale: PhotoViewComputedScale.contained * (0.5 + index / 10),
      maxScale: PhotoViewComputedScale.covered * 1.1,
      heroAttributes: PhotoViewHeroAttributes(tag: tag),
    );
  }
  void _editDyDialog() async {
    await showEditDialog(context: context, title: '保存图片');
  }

  Future<int> showEditDialog({
    @required BuildContext context,
    @required String title,
  }) {
    return showCustomBottomSheet(
        titleColor: AppColor.colorTheme,
        context: context,
        title: title,
        cancelTextColor: AppColor.colorDialog,
        titleClick: () {
          _saveImage();
          Navigator.pop(context);
        });
  }
  _saveImage() async {
    await getPerm();
    await capturePng();
  }

  Future getPerm() async {
    // 申请权限
    bool a = await await Permission.storage.request().isGranted;
    print(a);
    if (a == true) {
      print(a);
      print("已经打开");
    } else {
      toast("请打开存储权限");
      await Future.delayed(Duration(seconds: 1));
      print(a);
      openAppSettings();
    }
  }
  static int currentTimeMillis() {
    return new DateTime.now().millisecondsSinceEpoch;
  }
  Future<String> capturePng() async {
    EasyLoading.show(status: "保存中...");
    try {
      var response = await Dio().get(widget.thumbGalleryItems[currentIndex],
          options: Options(responseType: ResponseType.bytes));
      final result = await ImageGallerySaver.saveImage(
          Uint8List.fromList(response.data),
          quality: 60,
          name: "ziyu_${currentTimeMillis()}");
      print(result);
      EasyLoading.dismiss();
      toast("保存成功");
    } catch (e) {
      print(e);
      toast("保存失败:${e}");
      EasyLoading.dismiss();
    }
    return null;
  }
}
